package com.marketingcenter.service.impl;

import com.marketingcenter.entity.DiscountCard;
import com.marketingcenter.repository.DiscountCardRepository;
import com.marketingcenter.service.DiscountCardService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 折扣卡服务实现类
 */
@Service
public class DiscountCardServiceImpl extends PromotionServiceImpl<DiscountCard> implements DiscountCardService {

    @Autowired
    private DiscountCardRepository discountCardRepository;

    @Override
    protected JpaRepository<DiscountCard, Long> getRepository() {
        return discountCardRepository;
    }

    @Override
    public List<DiscountCard> findByStatus(Integer status) {
        return discountCardRepository.findByStatus(status);
    }

    @Override
    public List<DiscountCard> findActivePromotions() {
        LocalDateTime now = LocalDateTime.now();
        return discountCardRepository.findByStartTimeLessThanEqualAndEndTimeGreaterThanEqual(now, now);
    }

    @Override
    public boolean distributeDiscountCard(Long cardId, Long userId) {
        // 实际实现中需要记录用户领取折扣卡的信息
        // 这里仅做简单示例
        DiscountCard card = findById(cardId);
        if (card != null && card.getStatus() == 1) { // 1表示进行中
            // 检查领取数量限制
            if (countUserReceived(cardId, userId) >= card.getMaxPerUser()) {
                return false;
            }
            // 检查总发行量
            if (card.getReceivedQuantity() >= card.getTotalQuantity()) {
                return false;
            }
            // 增加已领取数量
            card.setReceivedQuantity(card.getReceivedQuantity() + 1);
            update(card);
            return true;
        }
        return false;
    }

    @Override
    public boolean useDiscountCard(Long cardId, Long userId, Long orderId) {
        // 实际实现中需要记录用户使用折扣卡的信息
        // 这里仅做简单示例
        DiscountCard card = findById(cardId);
        if (card != null && card.getStatus() == 1) { // 1表示进行中
            // 检查使用时间是否在有效期内
            LocalDateTime now = LocalDateTime.now();
            if (now.isBefore(card.getStartTime()) || now.isAfter(card.getEndTime())) {
                return false;
            }
            // 增加已使用数量
            card.setUsedQuantity(card.getUsedQuantity() + 1);
            update(card);
            return true;
        }
        return false;
    }

    @Override
    public int countUserReceived(Long cardId, Long userId) {
        // 实际实现中需要查询用户领取折扣卡的记录
        // 这里仅做简单返回，实际应用中需要连接到用户领取记录表
        return 0;
    }

}